//
//  Tjsp_Vm.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//

import RxSwift
import NetWorkCore
import ModelProtocol
import SwiftyJSON
import UtilCore
import RickonCore

/*
 owner:cy
 update:2016年12月13日17:57:04
 info: 首页数据
 VC:   HomePage_Vc
 model: HomePageModel
 */
class Tjsp_Vm :BaseList_Vm{
    /// 表示正在刷新中
    let loading = ActivityIndicator()
    /*
     接收返回的数据
     */
    /// 返回首页数据
    let productsElements = Variable<[HpProductModel]>([])
    
    /*
     设置参数
     */
    /// 表示正在刷新中
    let refreshing = Variable(false)
    init(
        input: (
        refreshTriger: Observable<String>,
        loadMoreTriger: Observable<String>
        )
        ) {
        super.init()
        /// 下拉刷新事件源
        let refreshSubject = Observable.of(
            input.refreshTriger,
            reloadTrigger.withLatestFrom(input.refreshTriger))
            .merge()
        refreshSubject
            .map{HomePageApi.getrecommendmore(page: 0, length: AppConfig.pageSize, id: $0) }
            .emeRequestApiForArray(HpProductModel.self,activityIndicator: loading)
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    /**
                     *  如果返回的数据正好相同 则默认还有数据
                     */
                    self.hasNextPage.value = data.count == AppConfig.pageSize
                    self.productsElements.value = data
                    self.page = 1
                case .failure(let error):
                    self.refresherror.onNext(error)
                }
            })
            .disposed(by: disposeBag)
        input.loadMoreTriger
            .map{HomePageApi.getrecommendmore(page:  self.page, length: AppConfig.pageSize, id: $0)}
            .emeRequestApiForArray(HpProductModel.self)
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    /**
                     *  如果返回的数据正好相同 则默认还有数据
                     */
                    self.hasNextPage.value = data.count == AppConfig.pageSize
                    self.productsElements.value  = self.productsElements.value + data
                    /**
                     *  需要修改page 页数
                     */
                    self.page = self.page +  1
                    
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .disposed(by: disposeBag)
    }
    
}
